//
//  ContactDetailViewController.m
//  leo
//
//  Created by YU-LIN LIU on 11/9/15.
//  Copyright © 2015 mdx. All rights reserved.
//

#import "ContactDetailViewController.h"


#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"
#import "AppDelegate.h"
@interface ContactDetailViewController ()

@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;

//相册参数
@property(nonatomic,strong) UIActionSheet *actionSheet;
@property(nonatomic,strong) UIImagePickerController *picker;
@property(nonatomic,strong) NSString *photoUrl;
@property(nonatomic,strong) NSString *photoName;

@end

@implementation ContactDetailViewController

@synthesize navLeftButton;
@synthesize navRightButton;
@synthesize contactPhoto;
@synthesize nameTextField;
@synthesize phoneTextField;
@synthesize deleteButton;
@synthesize contact;
@synthesize manager;
@synthesize camaraPhoto;

@synthesize imageContainerView;
@synthesize watchContact;
UITapGestureRecognizer *tapReconizerToPic;
//判断某个电话号码是否为管理员

-(BOOL)thePhoneIsManager:(NSString *)phone
{
    self.dataManager=[[DataManager alloc]init];
    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    
    NSArray *ManagersArray = [self.dataManager getManagerLists:watchId accountId:userId];
    for (int i=0;i<ManagersArray.count;i++)
    {
        Manager *manager=[ManagersArray objectAtIndex:i];
        if (manager.phone==phone){return YES;}
        if ([phone isEqualToString:manager.phone]){return YES;}
    }
    
    return NO;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [nameTextField resignFirstResponder];
    [phoneTextField resignFirstResponder];
}
-(void)dealloc
{
    contact=NULL;
    manager=NULL;
    self.syncManager=NULL;
    self.dataManager=NULL;
    self.actionSheet=NULL;
    self.picker=NULL;
    self.photoUrl=NULL;
    self.photoName=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"联系人";
    self.navigationItem.rightBarButtonItem=self.navRightButton;
    [self initDataProxy];
    [self initNavButton];
    //[self getContactDataFromServer];
    [self initData];
    [self beforeCamara];

    // Do any additional setup after loading the view from its nib.
}
-(void)getContactDataFromServer{
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    [self.syncManager getWatchContact:watchId completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if (result==SUCESS)
        {
            
        }
        else
        {
            [LeoMsg showMsg:description];
        }
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}
-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
}
- (void)initNavButton {
    /*
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate.isAdmin==NO)
    {
        self.deleteButton.enabled=NO;
        self.deleteButton.hidden=YES;
        self.navigationItem.rightBarButtonItem=nil;
        self.nameTextField.enabled=NO;
        self.phoneTextField.enabled=NO;
    }
    else
    {*/
        [navRightButton setTarget:self];
        [navRightButton setAction:@selector(save)];        
        [deleteButton addTarget:self action:@selector(verifyBeforeDelete) forControlEvents:UIControlEventTouchUpInside];
        //进入相册手势添加
        tapReconizerToPic = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setImg)];
        [self.imageContainerView addGestureRecognizer:tapReconizerToPic];
        nameTextField.delegate=self;
        phoneTextField.delegate=self;
    //}


}

-(void)viewWillAppear:(BOOL)animated
{
    //头像切圆代码
    self.contactPhoto.layer.cornerRadius = 120 / 2;
    self.contactPhoto.clipsToBounds = YES;
    
    if (manager!=nil)
    {
        self.deleteButton.hidden=YES;
        self.navigationItem.rightBarButtonItem=nil;
        camaraPhoto.hidden=YES;
    }
    if (watchContact!=nil)
    {
        self.deleteButton.hidden=YES;
        self.navigationItem.rightBarButtonItem=nil;
        camaraPhoto.hidden=YES;
    }


}
-(void)initDataFromWatch
{
    phoneTextField.text=watchContact.sim;
    if(watchContact.nickname!=NULL&&![watchContact.nickname isEqualToString:@"(null)"]&&![watchContact.nickname isEqualToString:@""])
    {
        nameTextField.text=watchContact.nickname;
    }
    else{nameTextField.text=@"未设置";}
    
    NSURL *url = [NSURL URLWithString:(watchContact.pic_url)];
    NSData *avatarImageData = [NSData dataWithContentsOfURL:url];
    
    NSRange range;
    NSString *photoNameString;
    range = [watchContact.pic_url rangeOfString:@"/headimg/"];
    if (range.location != NSNotFound) {
        NSLog(@"found at location = %d, length = %d",range.location,range.length);
        photoNameString=[watchContact.pic_url substringFromIndex:range.location];
        NSLog(@"%@",photoNameString);
        
    }else{
        NSLog(@"Not Found");
    }
    
    
    if(watchContact.pic_url!=NULL&&![watchContact.pic_url isEqualToString:@"(null)"]&&![watchContact.pic_url isEqualToString:@""])
    {
        NSString *headUrl=[NSString stringWithFormat:@"%@%@",[Tooler getDocumentDirectory],photoNameString];
        contactPhoto.image=[UIImage imageWithContentsOfFile:headUrl];
    }
    else
    {
        //默认头像
        contactPhoto.image = [UIImage imageNamed:@"avater_brother"];
        //contactPhoto.backgroundColor=[UIColor whiteColor];

    }
 
}
-(void)initDataFromManager
{
    phoneTextField.text=manager.phone;
    if(manager.nickName!=NULL&&![manager.nickName isEqualToString:@"(null)"]&&![manager.nickName isEqualToString:@""])
    {
        nameTextField.text=manager.nickName;
    }
    else{nameTextField.text=@"未设置";}
    
    NSURL *url = [NSURL URLWithString:(contact.photo_url)];
    NSData *avatarImageData = [NSData dataWithContentsOfURL:url];
    
    NSRange range;
    NSString *photoNameString;
    range = [manager.pic_url rangeOfString:@"/headimg/"];
    if (range.location != NSNotFound) {
        NSLog(@"found at location = %d, length = %d",range.location,range.length);
        photoNameString=[manager.pic_url substringFromIndex:range.location];
        NSLog(@"%@",photoNameString);
        
    }else{
        NSLog(@"Not Found");
    }
    
    
    if(manager.pic_url!=NULL&&![manager.pic_url isEqualToString:@"(null)"]&&![manager.pic_url isEqualToString:@""])
    {
        NSString *headUrl=[NSString stringWithFormat:@"%@%@",[Tooler getDocumentDirectory],photoNameString];
        contactPhoto.image=[UIImage imageWithContentsOfFile:headUrl];
    }
    else
    {
        //默认头像
        contactPhoto.image = [UIImage imageNamed:@"avater_brother"];
        //contactPhoto.backgroundColor=[UIColor whiteColor];

    }

}
-(void)initData
{
    if (manager!=nil)
    {
        [self initDataFromManager];
        [nameTextField setBorderStyle:UITextBorderStyleNone];
        [phoneTextField setBorderStyle:UITextBorderStyleNone];
        nameTextField.userInteractionEnabled = NO;
        phoneTextField.userInteractionEnabled = NO;
        if (tapReconizerToPic!=nil){
            [self.imageContainerView removeGestureRecognizer:tapReconizerToPic];  }      return;
    }
    
    if (watchContact!=nil)
    {
        [self initDataFromWatch];
        [nameTextField setBorderStyle:UITextBorderStyleNone];
        [phoneTextField setBorderStyle:UITextBorderStyleNone];
        nameTextField.userInteractionEnabled = NO;
        phoneTextField.userInteractionEnabled = NO;
        if (tapReconizerToPic!=nil){
            [self.imageContainerView removeGestureRecognizer:tapReconizerToPic];  }      return;
    }
    
    
    phoneTextField.text=contact.phoneNum;
    nameTextField.text=contact.contactname;
    
    NSURL *url = [NSURL URLWithString:(contact.photo_url)];
    NSData *avatarImageData = [NSData dataWithContentsOfURL:url];
    
    NSRange range;
    NSString *photoNameString;
    range = [contact.photo_url rangeOfString:@"/headimg/"];
    if (range.location != NSNotFound) {
        NSLog(@"found at location = %d, length = %d",range.location,range.length);
        photoNameString=[contact.photo_url substringFromIndex:range.location];
        NSLog(@"%@",photoNameString);
        
    }else{
        NSLog(@"Not Found");
    }
    
    
    if(contact.photo_url!=NULL&&![contact.photo_url isEqualToString:@"(null)"]&&![contact.photo_url isEqualToString:@""])
    {
        NSString *headUrl=[NSString stringWithFormat:@"%@%@",[Tooler getDocumentDirectory],photoNameString];
        contactPhoto.image=[UIImage imageWithContentsOfFile:headUrl];
    }
    else
    {
        //默认头像
        contactPhoto.image = [UIImage imageNamed:@"avater_brother"];
        //contactPhoto.backgroundColor=[UIColor whiteColor];

    }

//    if(contact.photo_url!=NULL&&![contact.photo_url isEqualToString:@"(null)"]&&![contact.photo_url isEqualToString:@""])
//    {
//        NSString *headUrl=[NSString stringWithFormat:@"%@%@",[Tooler getDocumentDirectory],contact.photo_url];
//        contactPhoto.image=[UIImage imageWithContentsOfFile:headUrl];
//    }
//    else
//    {
//        contactPhoto.image = [UIImage imageNamed:@"avater_brother"];
//    }

    
//    if (avatarImageData==NULL)
//    {
//        contactPhoto.image = [UIImage imageNamed:@"avater_brother"];
//    }
//    else
//    {
//        contactPhoto.image = [UIImage imageWithData:avatarImageData];
//    }
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
    //[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)setManager
{
    //[LeoMsg showMsg:@"主副管理员资料无法修改!"];
    [self.navigationController popViewControllerAnimated:YES];

}
- (void)save{
    
    if (manager!=nil)
    {
        [self setManager];
        return;
    }
    
    if((nameTextField.text==NULL)||([nameTextField.text isEqualToString:@""]))
    {
        [LeoMsg showMsg:@"姓名不能为空，请检查后再保存"];
        return;
    }
    
    
//    if (![self validateMobile:phoneTextField.text])
//    {
//        [LeoMsg showMsg:@"手机号码有误，请检查后再保存"];
//        return;
//        
//    }
    if ([LeoMsg ContactPhoneFormatIsWrong:phoneTextField.text])
    {
        return;
    }
    Contact *contact1=[[Contact alloc] init];
    contact1.phoneNum=phoneTextField.text;
    contact1.contactname=nameTextField.text;
    contact1.type=contact.type;
    //contact1.photoName=contact.photoName;
    contact1.groupId=contact.groupId;
    contact1.user_id=contact.user_id;
    
    if (self.photoName!=nil)
    {
        contact1.photo_url=self.photoUrl;
        contact1.photoName=self.photoName;
    }
    else
    {
        contact1.photoName=contact.photoName;
        contact1.photo_url=contact.photo_url;
    }
    contact1.deviceUid=contact.deviceUid;

//    contact1.photo_url=contact.photo_url;
//    contact1.deviceUid=contact.deviceUid;
    
    if ([self thePhoneIsManager:phoneTextField.text])
    {
        [LeoMsg showMsg:@"此号码已是管理员!"];
        return ;
    }

    if(self.dataManager==NULL)
    {
        [LeoMsg showMsg:@"程序发生错误，code is 17"];
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL||user.uid==NULL)
    {
        [LeoMsg showMsg:@"程序发生错误，code is 18"];
        return;
    }
    Watch *watch=[self.dataManager getActiveWatch:user.uid];
    if(watch==NULL||watch.deviceUid==NULL)
    {
        [LeoMsg showMsg:@"没有选中手表，code is 1"];
        return;
    }
    if([self.dataManager IsSameContact:watch.deviceUid contact:contact1 isNew:NO]==YES)
    {
        [LeoMsg showMsg:@"联系人已存在"];
        return;
    }
    [self.syncManager setWatchContact:contact1 completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        //[self callback:result retValue:retValue description:description];
        if (result==SUCESS)
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [self.navigationController popViewControllerAnimated:YES];
            [Tooler showHttpMsg:result description:description msg:@"修改联系人失败"];
        }

    }];

    
    
}

-(void)verifyBeforeDelete
{
    
    if (manager!=nil)
    {
        [LeoMsg showMsg:@"主副管理员无法删除!"];
        return;
    }

    
    if (contact.type==0)
    {
        [self deleteContact];
        return;
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:@"此联系人是紧急联系人，确认删除?"
                                                   delegate:self
                                          cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    [alert show];
    alert=nil;

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //NSString* msg = [[NSString alloc] initWithFormat:@"您按下的第%d个按钮！",buttonIndex];
    if (buttonIndex==0)
    {
        return;
    }
    else
    {
        [self deleteContact];
    }
    //[LeoMsg showMsg:@"123"];
}
- (void)deleteContact{

    
    
    //NSLog(@"%@",contact.contact_id);
    //NSLog(@"%@",contact.contactname);
    
    

    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    
    [self.syncManager deleteContact:watchId contactId:contact.user_id completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        //[self callback:result retValue:retValue description:description];
        if (result==SUCESS)
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [self.navigationController popViewControllerAnimated:YES];
            [Tooler showHttpMsg:result description:description msg:@"删除联系人失败"];

        }
    }];
    
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//相机相册部分
- (void)setImg{
    //NSLog(@"123");
    [self.actionSheet showInView:self.view];
    
}


-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self camera];
    }else if (buttonIndex == 1) {
        [self LocalPhoto];
    }else if(buttonIndex == 2) {
        
    }
    
}
-(void)beforeCamara
{
    self.actionSheet = [[UIActionSheet alloc]
                        initWithTitle:nil
                        delegate:self
                        cancelButtonTitle:nil
                        destructiveButtonTitle:nil
                        otherButtonTitles:@"拍照", @"从手机相册选择",@"取消",nil];
    self.actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    self.picker = [[UIImagePickerController alloc] init];
    self.picker.delegate = self;
    //设置选择后的图片可被编辑
    self.picker.allowsEditing = YES;
    
    self.picker.navigationBar.translucent =NO;
    
    [self.picker.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [self.picker.navigationBar setBarTintColor:[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1.0]];
}

-(void)LocalPhoto
{
    self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //[[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    [self presentViewController:self.picker animated:YES completion:nil];
}
-(void)camera
{
    self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //[[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    [self presentViewController:self.picker animated:YES completion:nil];
}
//取消选择
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        NSData *data=UIImageJPEGRepresentation(image, 0.3);
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [[Tooler getDocumentDirectory] stringByAppendingString:@"/headimg"];
        if([Tooler isDirectoryExist:DocumentsPath])
        {
            NSString *ts=[Tooler getTS];
            self.photoName=[NSString stringWithFormat:@"/headimg/image%@.jpg",ts];
            //得到选择后沙盒中图片的完整路径
            self.photoUrl = [[NSString alloc]initWithFormat:@"%@/image%@.jpg",DocumentsPath,ts];
            NSError *error;
            [data writeToFile:self.photoUrl options:NSDataWritingFileProtectionComplete error:&error];
            if(error==NULL)
            {
                self.contactPhoto.image=[UIImage imageNamed:self.photoUrl];
            }
            
        }
        [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
        [self.picker dismissViewControllerAnimated:YES completion:nil];
        
    }
    
}
//***键盘遮挡部分
//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGFloat kbHeight =258;
    int INTERVAL_KEYBOARD=258;
    
    CGFloat offset = textField.frame.origin.y + 32 - (self.view.frame.size.height - kbHeight);//键盘高度300
    //CGFloat offset = (textField.frame.origin.y+textField.frame.size.height+INTERVAL_KEYBOARD) - (self.view.frame.size.height - kbHeight);
    
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    NSLog(@"%f",offset);
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}

//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}

//校验手机号码
- (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
//        NSString *parten =@"[0-9]{11}";
//        if ([self checkRegular:parten Target:mobileNum]&&(mobileNum.length==11)){return YES;}
//        parten =@"[0-9]{5}";
//        if ([self checkRegular:parten Target:mobileNum]&&(mobileNum.length==5)){return YES;}
//        parten =@"[0-9]{5}";
        return NO;
    }
}
-(BOOL)checkRegular:(NSString*)parten Target:(NSString*)staString
{
    //NSString *staString =mobileNum;
    
    //NSString *parten =@"[0-9]{11}";
    
    NSError* error = NULL;
    
    NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:parten options:nil error:&error];
    
    NSArray* match = [reg matchesInString:staString options:NSMatchingCompleted range:NSMakeRange(0, [staString length])];
    
    if (match.count != 0)
    {
        for (NSTextCheckingResult *matc in match)
        {
            NSRange range = [matc range];
            NSLog(@"%lu,%lu,%@",(unsigned long)range.location,(unsigned long)range.length,[staString substringWithRange:range]);
        }
        return YES;
    }
    return NO;
}

@end
